package com.heima.comment.controller;

import com.heima.comment.entity.vo.ApCommentVo;
import com.heima.comment.service.ApCommentService;
import com.heima.model.comment.dto.CommentLikeDto;
import com.heima.model.comment.dto.CommentListDto;
import com.heima.model.comment.dto.CommentSaveDto;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang.StringUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;

@RestController
@RequestMapping("/api/v1/comment")
@Api(value = "APP端评论管理", tags = "评论管理")
public class ApCommentController {

    @Resource
    private ApCommentService apCommentService;

    /**
     * 发表评论
     *
     * @param dto
     * @return
     */
    @PostMapping(path = "/save")
    @ApiOperation("发表评论")
    public ResponseResult save(@RequestBody CommentSaveDto dto) {
        if (StringUtils.isEmpty(dto.getContent()) || dto.getArticleId() == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_REQUIRE);
        }

        return apCommentService.saveComment(dto.getArticleId().toString(), dto.getContent());
    }


    /**
     * 评论点赞
     *
     * @param dto
     * @return
     */
    @PostMapping(path = "/like")
    @ApiOperation("评论点赞")
    public ResponseResult like(@RequestBody CommentLikeDto dto) {
        if (StringUtils.isEmpty(dto.getCommentId())) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_REQUIRE);
        }
        if (dto.getOperation() != 0 && dto.getOperation() != 1) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }

        return apCommentService.like(dto.getCommentId(), dto.getOperation());
    }

    /**
     * 查询文章评论列表
     *
     * @param dto
     * @return
     */
    @PostMapping(path = "/load")
    @ApiOperation("查询文章评论列表")
    public ResponseResult<List<ApCommentVo>> load(@RequestBody CommentListDto dto) {
        if (dto.getArticleId() == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_REQUIRE);
        }
        //最小时间校验
        Date minTime = dto.getMinDate() == null ? new Date() : dto.getMinDate();
        //每页展示数据条数校验
        Integer size = dto.getSize() == null || dto.getSize() <= 0 ? 10 : dto.getSize();
        size = Math.min(size, 50);

        return apCommentService.load(dto.getArticleId().toString(), minTime, size);
    }



}
